package hotel.quartz.oversea.job.task;

import com.alibaba.fastjson.JSON;
import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.constant.CommonUrlConstants;
import hotel.base.oversea.utils.DateUtil;
import hotel.base.oversea.utils.Result;
import hotel.quartz.oversea.entity.SysApiLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.UUID;


@Slf4j
@Component
public class JobSaveApiLogTask {
    private String timestamp = "Msalt"+String.valueOf(System.currentTimeMillis());

    @Autowired
    private RestTemplate restTemplate;

    //@Async 标识这个方法异步执行，可返回void或Future
    @Async
    public void execute(String obj,String method,String className,String remark,String paramsJson){

        SysApiLog sysApiLog = new SysApiLog();
        sysApiLog.setId(UUID.randomUUID().toString());
        sysApiLog.setSystemName(method);
        sysApiLog.setClassName(className);
        sysApiLog.setRemark(remark);
        sysApiLog.setJson(obj==null?null:obj.toString());
        sysApiLog.setParamJson(paramsJson);
        sysApiLog.setCreateTime(new Date());
        sysApiLog.setModifyTime(sysApiLog.getCreateTime());

        log.info("JobSaveApiLogTask {} >>>>>>>>> 异步线程 保存系统日志  开始执行时间：{}",timestamp, DateUtil.getNowTime());

        try{
            //发起请求
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.valueOf("application/json;UTF-8"));
            HttpEntity<String> strEntity = new HttpEntity<String>(JSON.toJSONString(sysApiLog),headers);
            String responseStr = restTemplate.postForObject(CommonUrlConstants.ADMIN_HOST+"/sysApiLog/save",strEntity, String.class);//?access_token=+accessToken
            Result response = null;
            try {
                response = JSON.parseObject(responseStr, Result.class);
            }catch (Exception e){
                log.error("////////////////////////JobSaveApiLogTask parseObject异常：{}", JSON.toJSONString(response));
                e.printStackTrace();
                response = new Result<>("转化result异常："+responseStr,-1);
            }
            if(CommonConstants.SUCCESS==response.getCode()){
            }else{
                log.error("////////////////////////JobSaveApiLogTask 保存日志到sysApiLog返回失败：{}", JSON.toJSONString(response));
            }
        }catch (Exception e){
            log.error("JobSaveApiLogTask {} >>>>>>>>> 异步线程 保存系统日志  异常catch：{},{}",timestamp, DateUtil.getNowTime(),e.getMessage());
            e.printStackTrace();
        }


    }


}
